package com.chenglu.android.order;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chenglu.android.R;
import com.chenglu.android.common.base.BaseFullScreenActivity;
import com.chenglu.android.common.base.Global;
import com.chenglu.android.common.net.Constant;
import com.chenglu.android.common.utils.BaseDialog;
import com.chenglu.android.common.utils.LogUtils;
import com.chenglu.android.common.utils.StatusBarUtil;
import com.chenglu.android.common.utils.ToastUtils;
import com.chenglu.android.common.utils.Utils;
import com.chenglu.android.goodsinfo.infoutils.GoodsInfoUtils;
import com.chenglu.android.logistics.LogisticsActivity;
import com.chenglu.android.mine.bean.CommonDataBean;
import com.chenglu.android.order.adapter.AllOrderAdapter;
import com.chenglu.android.order.adapter.TabTitleAdapter;
import com.chenglu.android.order.bean.OrderInfoBean;
import com.chenglu.android.order.mvp.contract.OrderContract;
import com.chenglu.android.order.mvp.presenter.OrderPresenter;
import com.chenglu.android.ordercomment.OrderCommentActivity;
import com.chenglu.android.orderinfo.OrderInfoActivity;
import com.chenglu.android.orderinfo.OrderInfoUtils;
import com.chenglu.android.orderinfo.bean.OrderDetailBean;
import com.chenglu.android.orderinfo.bean.QrcodeBean;
import com.chenglu.android.payment.PayUtils;
import com.chenglu.android.payment.adapter.OrderPaytypeAdapter;
import com.chenglu.android.payment.bean.CouponListBean;
import com.chenglu.android.payment.bean.PayOrderBean;
import com.chenglu.android.payment.bean.TenantIdPayMethod;
import com.luck.picture.lib.decoration.WrapContentLinearLayoutManager;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.animator.PopupAnimator;
import com.lxj.xpopup.core.BottomPopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author: lyj
 * @Created: by Copyright 2023/10/14 Guangzhou Hongma Technology Co., Ltd. All rights reserved.
 * @Description：
 */
public class OrderActivity extends BaseFullScreenActivity<OrderPresenter> implements OrderContract.View {

    public  static  final  String STATUS  = "status";

    @BindView(R.id.ic_back)
    ImageView icBack;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.rv_order_title)
    RecyclerView rvOrderTitle;
    @BindView(R.id.rv_order_data)
    RecyclerView rvOrderData;
    @BindView(R.id.smartrefreshlayout)
    SmartRefreshLayout smartrefreshlayout;
    @BindView(R.id.ll_loading_data)
    LinearLayout llLoadingData;
    @BindView(R.id.iv_no_data)
    ImageView ivNoData;
    @BindView(R.id.tv_no_data)
    TextView tvNoData;
    @BindView(R.id.ll_loading_no_data)
    LinearLayout llLoadingNoData;

    private TabTitleAdapter titleAdapter;
    private int mCurrentPosition;
    private int current = 1;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);
        ButterKnife.bind(this);

        StatusBarUtil.immersive(this);
        StatusBarUtil.setPaddingSmart(this, toolbar);
        tvTitle.setText("我的订单");
        status =  getIntent().getStringExtra(STATUS);
        mPresenter = new OrderPresenter();
        mPresenter.attachView(this);


        initTabTitleAdapter();
        //初始化数据
        initAdapter();

        initRefreshLayout();


    }

    private String status;

    //传递的参数类型
    private Map<String, String> setOrderMap(String status, String resourceType) {
        Map<String, String> map = new HashMap<>();
        if (status.equals("0")) {

        }else {
            map.put("status", status);
        }

        map.put("current", current + "");
        //来源类型 1-默认板块 2-积分商城
        map.put("resourceType", resourceType);

        map.put("size", Constant.SIZE + "");
        return map;
    }


    @Override
    protected void onResume() {
        super.onResume();
        //如果没有做操作 不需要刷新
        current= 1;
        list.clear();
        mPresenter.getOrderList(getToken(), setOrderMap(status, Constant.one));
    }

    //标题数据的列表
    private void initTabTitleAdapter() {
        List<String> stringList = new ArrayList<>();
        stringList.add(getResources().getString(R.string.order_all));
        stringList.add(getResources().getString(R.string.order_waitpay));
        stringList.add(getResources().getString(R.string.order_illustrate));
        stringList.add(getResources().getString(R.string.order_comment));

        titleAdapter = new TabTitleAdapter(mContext, stringList);
        rvOrderTitle.setLayoutManager(new LinearLayoutManager(mContext,
                LinearLayoutManager.HORIZONTAL, false));

        rvOrderTitle.setAdapter(titleAdapter);
        titleAdapter.setThisPosition(Integer.parseInt(status));
        titleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                titleAdapter.setThisPosition(position);
                mCurrentPosition = position;
                switch (position) {
                    case 0:
                        status = "";
                        current = 1;
                        list.clear();

                        mPresenter.getOrderList(getToken(), setOrderMap(status, Constant.one));
                        break;
                    case 1:
                        status = "1";
                        current = 1;
                        list.clear();
                        mPresenter.getOrderList(getToken(), setOrderMap(status, Constant.one));
                        break;
                    case 2:
                        status = "3";
                        current = 1;
                        list.clear();
                        mPresenter.getOrderList(getToken(), setOrderMap(status, Constant.one));
                        break;
                    case 3:
                        status = "4";
                        current = 1;
                        list.clear();
                        mPresenter.getOrderList(getToken(), setOrderMap(status, Constant.one));
                        break;
                }
            }
        });


    }


    //刷新
    private void initRefreshLayout() {

        smartrefreshlayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //id 需要传参过来
                current = 1;
                //需要清空数据再加
                list.clear();
                mPresenter.getOrderList(getToken(), setOrderMap(status, Constant.one));


            }
        });
        smartrefreshlayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                current += 1;
                mPresenter.getOrderList(getToken(), setOrderMap(status, Constant.one));

            }
        });
    }

    @Override
    public void onNetOutTimeError(String tag) {
        super.onNetOutTimeError(tag);

        stopRefresh(smartrefreshlayout);


    }

    @Override
    public void onNetWorkError(Object tag) {
        super.onNetWorkError(tag);
    }

    List<OrderInfoBean.Data.Records> list = new ArrayList<>();

    private AllOrderAdapter allAdapter;
    private int mOrderPosition;

    private void initAdapter() {
        allAdapter = new AllOrderAdapter(OrderActivity.this, list);
        rvOrderData.setLayoutManager(new WrapContentLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
//        rvCoupon.setLayoutManager(new LinearLayoutManager(context));
        rvOrderData.setAdapter(allAdapter);

        allAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                OrderInfoUtils.jumpOrderInfoActivity(mContext,allAdapter.getItem(position));

            }
        });

        allAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {

                    case R.id.tv_order_btn1:
                        //点击就赋值
                        mOrderPosition = position;

                        TextView tvcheck = view.findViewById(R.id.tv_order_btn1);
                        String tv1 = tvcheck.getText().toString();
                        if (tv1.equals(getResources().getString(R.string.order_cancel))) {

                            BaseDialog.showDialog(mContext, "是否取消订单", "取消", "确定", new OnConfirmListener() {
                                @Override
                                public void onConfirm() {

                                    //取消订单的接口
                                    mPresenter.getOrderCancel(getToken(), allAdapter.getData().get(position).getId());

                                }
                            }, false);

                        } else if (tv1.equals(getResources().getString(R.string.order_look_logistics))) {
                            //查看物流
                            Intent intent = new Intent(mContext, LogisticsActivity.class);
                            intent.putExtra("orderNo", allAdapter.getData().get(position).getOrderNo());
                            startActivity(intent);

                        } else if (tv1.equals(getResources().getString(R.string.order_delete))) {
                            LogUtils.e("删除订单id=" + allAdapter.getData().get(position).getId());
                            BaseDialog.showDialog(mContext, "是否删除订单", "取消", "确定", new OnConfirmListener() {
                                @Override
                                public void onConfirm() {
//                                    LogUtils.e("删除订单id="+ allAdapter.getData().get(position).getId());
                                    //取消订单的接口
                                    mPresenter.getOrderRemove(getToken(), allAdapter.getData().get(position).getId());

                                }
                            }, false);
                        } else if (tv1.equals(mContext.getResources().getString(R.string.order_comment_message))) {
                            Intent commentInent = new Intent(mContext, OrderCommentActivity.class);
                            Bundle bundle = new Bundle();
                            OrderInfoBean.Data.Records records = allAdapter.getData().get(position);
                            bundle.putSerializable(OrderCommentActivity.ORDERLIST, records);
                            commentInent.putExtra(OrderCommentActivity.ORDERNO, allAdapter.getData().get(position).getOrderNo());
                            commentInent.putExtras(bundle);
                            mContext.startActivity(commentInent);
                        }

                        break;
                    case R.id.tv_order_btn2:
                        mOrderPosition = position;
                        TextView tvcomment = view.findViewById(R.id.tv_order_btn2);
                        String tv2 = tvcomment.getText().toString();
                        if (tv2.equals("评价")) {

                            Intent commentInent = new Intent(mContext, OrderCommentActivity.class);
                            Bundle bundle = new Bundle();
                            OrderInfoBean.Data.Records records = allAdapter.getData().get(position);
                            bundle.putSerializable(OrderCommentActivity.ORDERLIST, records);
                            commentInent.putExtra(OrderCommentActivity.ORDERNO, allAdapter.getData().get(position).getOrderNo());
                            commentInent.putExtras(bundle);
                            mContext.startActivity(commentInent);
                        }
                        //再次购买
                        else if (tv2.equals(getResources().getString(R.string.order_buy_again))) {
                            if (!allAdapter.getData().get(mOrderPosition).getOrderDetails().isEmpty()) {
                                GoodsInfoUtils.goodsInfo(mContext, allAdapter.getData().get(mOrderPosition).getOrderDetails().get(0).getGoodsId()
                                       , allAdapter.getData().get(mOrderPosition).getShopsTypeId());
                            }
                            //立即支付
                        } else if (tv2.equals(getResources().getString(R.string.order_immediate_payment))) {
                            //弹出付款对话框
                            mPresenter.getenantIdPayMethod(getToken(), Constant.APPCLIENT, allAdapter.getData().get(mOrderPosition).getTenantId());

                        } else if (tv2.equals(getResources().getString(R.string.order_confirm_receipt))) {
                            //确认收货
                            mPresenter.getOrderReceiving(getToken(), allAdapter.getData().get(mOrderPosition).getId());
                        }

                        break;
                    case R.id.tv_order_btn3:
                        //联系客服 待开发
                        TextView btn3 = view.findViewById(R.id.tv_order_btn3);
                        ToastUtils.show("近期开放");
                        break;
                }

            }
        });
    }

    @OnClick({R.id.ll_back, R.id.tv_no_data})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.tv_no_data:
                break;
        }
    }


    @Override
    public void getCouponList(CouponListBean bean) {

    }

    BottomPopup showpayTypePopup;

    @Override
    public void getenantIdPayMethod(TenantIdPayMethod bean) {
        //弹出支付的对话框
        showpayTypePopup = new BottomPopup(this);
        showpayTypePopup.setPayMethodList(bean.getData());
        new XPopup.Builder(this)
                .moveUpToKeyboard(false)
                .enableDrag(false)
                .animationDuration(150)
                .asCustom(showpayTypePopup)
                .show();

    }

    //对话框选择的参数类型

    private int mPayposition;

    class BottomPopup extends BottomPopupView {

        ImageView ivDialogDelete;
        Button btnPayOrder;
        RecyclerView rvPay;

        //注意：自定义弹窗本质是一个自定义View，但是只需重写一个参数的构造，其他的不要重写，所有的自定义弹窗都是这样。
        public BottomPopup(@NonNull Context context) {
            super(context);
        }

        // 返回自定义弹窗的布局
        @Override
        protected int getImplLayoutId() {
            return R.layout.dialog_pay_order;
        }

        // 执行初始化操作，比如：findView，设置点击，或者任何你弹窗内的业务逻辑
        @Override
        protected void onCreate() {
            super.onCreate();
            //创建的时候默认的金豆支付


            ivDialogDelete = findViewById(R.id.iv_dialog_delete);
            btnPayOrder = findViewById(R.id.btn_pay_order);
            rvPay = findViewById(R.id.rv_pay);

         OrderPaytypeAdapter orderPaytypeAdapter = new OrderPaytypeAdapter(mContext, R.layout.item_pay_method, payMethodList);
            rvPay.setLayoutManager(new LinearLayoutManager(mContext));
            rvPay.setAdapter(orderPaytypeAdapter);
            orderPaytypeAdapter.setThisPosition(0);
            orderPaytypeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                    mPayposition = position;
                    orderPaytypeAdapter.setThisPosition(position);

                }
            });

            btnPayOrder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    需要二次确认
                    dismiss();
                    BaseDialog.showDialog(mContext, "确定使用" + orderPaytypeAdapter.getData().get(mPayposition).getDescriptions() + "支付吗", "取消", "确定", new OnConfirmListener() {
                        @Override
                        public void onConfirm() {

                            JSONObject jsonObject = PayUtils.setPayParam(allAdapter.getData().get(mOrderPosition).getOrderNo(), orderPaytypeAdapter.getData().get(mPayposition).getPayType(), orderPaytypeAdapter.getData().get(mPayposition).getId());

                            mPresenter.getPayOrder(getToken(), Utils.getRequestBody(jsonObject));


                        }
                    }, false);


                }
            });

            ivDialogDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });


        }

        // 设置最大宽度，看需要而定，
        @Override
        protected int getMaxWidth() {
            return super.getMaxWidth();
        }

        @Override
        protected int getMaxHeight() {
            return super.getMaxHeight();
        }

        @Override
        protected PopupAnimator getPopupAnimator() {
            return super.getPopupAnimator();
        }

        protected int getPopupWidth() {
            return 0;
        }

        protected int getPopupHeight() {
            return 0;
        }


        private List<TenantIdPayMethod.Data> payMethodList;

        public List<TenantIdPayMethod.Data> getPayMethodList() {
            return payMethodList;
        }

        public void setPayMethodList(List<TenantIdPayMethod.Data> payMethodList) {
            this.payMethodList = payMethodList;
        }

    }

    @Override
    public void getPayOrder(PayOrderBean bean) {
        ToastUtils.show("支付成功");
        allAdapter.getData().get(mCurrentPosition).setStatus(2);
        allAdapter.notifyDataSetChanged();
    }

    boolean isAddFooterView = true;

    @Override
    public void getOrderList(OrderInfoBean bean) {

        stopRefresh(smartrefreshlayout);
//        LogUtils.e(new Gson().toJson(bean.getData().getRecords()));
        if (bean.getData().getRecords().size() > 0) {

            llLoadingData.setVisibility(View.VISIBLE);
            llLoadingNoData.setVisibility(View.GONE);
            for (int i = 0; i < bean.getData().getRecords().size(); i++) {
                //添加集合中banner的数据
                list.add(bean.getData().getRecords().get(i));
            }
            LogUtils.w("全部 list" + list.size());
            if (bean.getData().getTotal() < Constant.SIZE) {
                smartrefreshlayout.setEnableRefresh(false);
            }
            if (current * Constant.SIZE >= bean.getData().getTotal()) {
                smartrefreshlayout.setEnableLoadMore(false);

                if (isAddFooterView) {
                    View inflate = Global.inflate(R.layout.loadmore_addfooter_layout);
                    inflate.findViewById(R.id.tv_no_more).setBackgroundColor(getResources().getColor(R.color.color_f6f6f6));
                    allAdapter.addFooterView(inflate);
                    isAddFooterView = false;
                }


            } else {
                isAddFooterView = true;
                allAdapter.removeAllFooterView();
                smartrefreshlayout.setEnableLoadMore(true);

            }
            allAdapter.notifyDataSetChanged();
        } else {
            if (list.isEmpty()) {
                llLoadingData.setVisibility(View.GONE);
//                llLoadingNoData.setBackground(getResources().getDrawable(R.drawable.corners_f6f6f6_default));
                llLoadingNoData.setVisibility(View.VISIBLE);
            }

        }
    }


    @Override
    public void getOrderCancel(CommonDataBean bean) {

        ToastUtils.show("取消成功");
        allAdapter.getData().get(mOrderPosition).setStatus(0);
        allAdapter.notifyDataSetChanged();
    }


    @Override
    public void getOrderRemove(CommonDataBean bean) {
        ToastUtils.show("删除成功");

        list.remove(mOrderPosition).getId();
        allAdapter.setNewData(list);
//        allAdapter.getData().get(mOrderPosition).setStatus(0);
        allAdapter.notifyDataSetChanged();
    }


    @Override
    public void getOrderReceiving(CommonDataBean bean) {

        ToastUtils.show(bean.getMsg());
        allAdapter.getData().get(mOrderPosition).setStatus(4);
        allAdapter.notifyDataSetChanged();
    }

    @Override
    public void getOrderInfo(OrderDetailBean bean) {

    }

    @Override
    public void getQrCodeInfo(QrcodeBean bean) {

    }


}
